#!/usr/bin/python2.5
#
# Copyright 2010 Felix Kerekes.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Request handlers for an admin to manage data seeding operations.
"""

__authors__ = [
    '"Felix Kerekes" <sttwister@gmail.com>',
  ]


from django.utils import simplejson
from django.http import HttpResponseForbidden, HttpResponse

from seeder.models_logic import logic as seeder_models_logic
from seeder.providers import logic as seeder_providers_logic
from seeder.logic import logic as seeder_logic
from seeder.logic import Error

from google.appengine.ext import webapp

import json
import logging

class JSONRPCHandler(webapp.RequestHandler, json.JSONRPC):

  def post(self):
      response, code = self.handleRequest(self.request.body, self.HTTP_POST)
      self.response.headers['Content-Type'] = 'application/json'
      self.response.set_status(code)
      self.response.out.write(response)

  def get(self):
      response, code = self.handleRequest(self.request.body, self.HTTP_GET)
      self.response.headers['Content-Type'] = 'application/json'
      self.response.set_status(code)
      self.response.out.write(response)

  def json_getData(self):
    response = {}

    response['models'] = seeder_models_logic.getModelsData()
    response['providers'] = seeder_providers_logic.getProvidersData()
    response['providers_mapping'] = seeder_providers_logic.getProvidersMapping()

    return response

  def json_testProvider(self, data):
    """Tests a parameter configuration for a data provider and return a sample
    value or an error message as JSON data.
    """
    value = seeder_logic.testProvider(data)

    return value

  def json_seed(self, data):

    try:
      seeder_logic.validateConfiguration(data)
    except Error, e:
      raise json.JSONRPCError("Error validating configuration sheet: %s" % e)

    seeder_logic.startMapReduce(data)

